<template>
  <el-card shadow="hover" class="category-tree-card">
    <template #header>
      <div class="card-header">
        <span>题库选择</span>
        <el-select
          v-model="selectedBankId"
          placeholder="请选择题库"
          clearable
          filterable
          remote
          :remote-method="handleBankSearch"
          :loading="bankLoading"
          @change="handleBankChange"
        >
          <el-option
            v-for="item in bankOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-switch
          v-if="isAdmin"
          v-model="viewAllBanks"
          active-text="查看所有题库"
          @change="handleViewAllChange"
        />
      </div>
    </template>
    
    <div class="tree-container">
      <el-tree
        ref="categoryTreeRef"
        :data="categoryTreeData"
        :props="{
          label: 'name',
          children: 'children'
        }"
        node-key="id"
        :default-expanded-keys="expandedKeys"
        :highlight-current="true"
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <span>{{ node.label }} ({{ data.questionCount || 0 }})</span>
        </template>
      </el-tree>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { pageEtQuestionBank } from '/@/api/main/et-question-bank';
import { getEtQuestionCateTree } from '/@/api/main/et-question-cate';
import { useUserInfo } from '/@/stores/userInfo';

interface QuestionBank {
  id: number;
  name: string;
}

interface QuestionCategory {
  id: number;
  name: string;
  children?: QuestionCategory[];
  questionCount?: number;
}

const emit = defineEmits(['update:bankId', 'update:categoryId']);

const categoryTreeRef = ref();
const selectedBankId = ref<number>();
const bankOptions = ref<QuestionBank[]>([]);
const categoryTreeData = ref<QuestionCategory[]>([]);
const expandedKeys = ref<number[]>([]);
const bankLoading = ref(false);
const bankParams = ref({
  page: 1,
  pageSize: 10,
  searchKey: '',
  total: 0
});
const viewAllBanks = ref(false);
const isAdmin = ref(useUserInfo().userInfos?.roles?.includes('superAdmin'));

// 获取题库列表 - 改为搜索模式
const getBankOptions = async (keyword = '') => {
  try {
    bankLoading.value = true;
    const res = await pageEtQuestionBank({
      page: 1,
      pageSize: 50, // 增加一次性加载的数量
      searchKey: keyword
    });
    
    if (res.data.result) {
      bankOptions.value = res.data.result.items || [];
    }
  } catch (error) {
    console.error('获取题库列表失败:', error);
    ElMessage.error('获取题库列表失败');
  } finally {
    bankLoading.value = false;
  }
};

// 处理搜索
const handleBankSearch = async (query: string) => {
  if (query) {
    await getBankOptions(query);
  } else {
    await getBankOptions();
  }
};

// 监听题库ID变化
watch(() => selectedBankId.value, async (newVal) => {
  if (newVal) {
    await loadCategoryTree();
  } else {
    categoryTreeData.value = [];
  }
});

// 处理题库切换
const handleBankChange = async (bankId: number) => {
  try {
    selectedBankId.value = bankId;
    emit('update:bankId', bankId);
    // 立即加载分类树
    await loadCategoryTree();
  } catch (error) {
    console.error('题库切换失败:', error);
    ElMessage.error('题库切换失败');
  }
};

// 加载分类树数据
const loadCategoryTree = async () => {
  try {
    if (!selectedBankId.value) {
      categoryTreeData.value = [];
      return;
    }
    const res = await getEtQuestionCateTree(selectedBankId.value);
    if (res.data.result) {
      // 后端已经返回树形结构，不需要再转换
      categoryTreeData.value = res.data.result;
      // 获取所有节点的ID作为展开键
      const getAllKeys = (nodes: QuestionCategory[]): number[] => {
        let keys: number[] = [];
        nodes.forEach(node => {
          keys.push(node.id);
          if (node.children?.length) {
            keys = keys.concat(getAllKeys(node.children));
          }
        });
        return keys;
      };
      expandedKeys.value = getAllKeys(categoryTreeData.value);
    } else {
      categoryTreeData.value = [];
    }
  } catch (error) {
    console.error('加载分类树失败:', error);
    ElMessage.error('加载分类树失败');
    categoryTreeData.value = [];
  }
};

// 处理节点点击
const handleNodeClick = (data: QuestionCategory) => {
  emit('update:categoryId', data.id);
};

// 处理查看所有题库开关
const handleViewAllChange = async () => {
  bankParams.value.page = 1;
  await getBankOptions();
};

// 初始化
onMounted(async () => {
  try {
    await getBankOptions(); // 初始加载
    if (bankOptions.value.length > 0) {
      selectedBankId.value = bankOptions.value[0].id;
      emit('update:bankId', selectedBankId.value);
      await loadCategoryTree();
    }
  } catch (error) {
    console.error('初始化失败:', error);
    ElMessage.error('初始化失败');
  }
});
</script>

<style lang="scss" scoped>
.category-tree-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  :deep(.el-card__header) {
    padding: 10px;
  }
  
  :deep(.el-card__body) {
    flex: 1;
    padding: 10px;
    overflow: hidden;
  }
  
  .card-header {
    display: flex;
    flex-direction: column;
    gap: 8px;
    
    .el-select {
      width: 100%;
    }
  }

  .tree-container {
    height: 100%;
    overflow-y: auto;
    
    &::-webkit-scrollbar {
      width: 6px;
    }
    
    &::-webkit-scrollbar-thumb {
      background-color: #ddd;
      border-radius: 3px;
    }
    
    &::-webkit-scrollbar-track {
      background-color: #f5f5f5;
    }
  }
}
</style> 